package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.constant.MemberConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();
        //设计会员默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        //检查用户名和手机号唯一
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());
        //设置参数
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        //密码要进行加密处理,不可逆，MD5不能直接用来进行加密，可以彩虹表破解。
        //盐值加密,随机值
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(password);
        //其它的默认信息
        //保存
        memberDao.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao memberDao = this.baseMapper;
        Long mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }

    }


    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        MemberDao memberDao = this.baseMapper;
        Long usernameCount = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (usernameCount > 0) {
            throw new UsernameExistException();
        }


    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //查询账号或手机号是否存在
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (memberEntity != null) {
            //查询密码
            String passwordDb = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            if (passwordEncoder.matches(password, passwordDb)) {
                //账号密码正确
                return memberEntity;

            } else {
                //账号或密码不正确
                return null;
            }

        } else {

            //账号或密码不正确
            return null;
        }


    }

    @Override
     public MemberEntity login(SocialUser socialUser) throws Exception {
        //具有登录和注册逻辑

        //1、判断当前社交用户是否已经登录过系统，由于返回accesstoken时未带id,所以还要查询到ID，然后用ID去数据库查询是否登录过。
        //查询当前社交用户的社交账号信息（用户名、id、header）
        Map<String,String> query = new HashMap<>();
        String accessToken = socialUser.getAccess_token();
        query.put("access_token",accessToken);
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), query);
        if (response.getStatusLine().getStatusCode() == 200) {
            //查询成功
            String json = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(json);
            String username = jsonObject.getString("name");
            String socialUid = jsonObject.getString("id");
//            String heaader = jsonObject.getString("avatar_url");
            //查询数据库是否登录过
            MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUid));
            if (memberEntity != null) {
                // todo 这个用户已经注册过
                return memberEntity;

            } else {
                //2、没有查到当前社交用户对应的记录我们就需要注册一个,组装数据
                MemberEntity register = new MemberEntity();
//                register.setAccessToken(accessToken);
                register.setUsername(username);
                register.setSocialUid(socialUid);
//                register.setHeader(heaader);
                register.setLevelId(MemberConstant.MemberLevelEnum.DEFAULT.getCode());
                // todo 把用户信息插入到数据库中
                baseMapper.insert(register);

             return register;
//
            }
        }else{
            return null;
        }
    }



}